# encodint:utd8
import traceback
from ccpm.collogger import Log
import sys
import os
import json
from mgamedev.py_lib.decorator import singleton     # noqa
from mgamedev.py_lib.luabase import LuabaseTool  # noqa
from ccpm.constants import Constant


def get_fileconf(fname):
    relstatic = os.path.relpath(
        Constant.STATIC_ENV_PATH, Constant.INSTALL_PATH)
    # debug
    static_f = os.path.join(os.getcwd(), os.path.join(relstatic, fname))
    if os.path.isfile(static_f):
        return static_f
    else:
        return os.path.join(Constant.STATIC_ENV_PATH, fname)


@singleton
class GConf(LuabaseTool):

    GCONF_KEYS = "G_CONFS"

    def __init__(self):
        super().__init__()
        self._f_luaconf = get_fileconf(Constant.CONFIG_FILE)
        self.__chk_conf()

    def __chk_conf(self):
        self.lua_dofile(self._f_luaconf)
        try:
            l_conf = self.lua_val(self.GCONF_KEYS)
            self._p_confs = l_conf

        except Exception as err:
            print(err)
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print(traceback.print_tb(exc_traceback))
            Log().error("Init global-config raise error!Chk it !")
            sys.exit(1)

    def get(self, gkey):
        return self._p_confs[gkey]

    def val(self, vkey):
        return self.lua_val(self.GCONF_KEYS)[vkey]


@singleton
class PluginConf(LuabaseTool):
    PLUGIN_CONFS_KEYS = "PLUGIN_CONFS"
    PLUGIN_LISTS_KEYS = "PLUGIN_LISTS"

    def __init__(self):
        super().__init__()
        conf = Constant.CONFIG_FILE
        self._f_luaconf = get_fileconf(conf)
        self._p_confs = dict()
        self.__chk_conf()

    def __chk_conf(self):
        self.lua_dofile(self._f_luaconf)
        try:
            l_conf = self.lua_val(self.PLUGIN_CONFS_KEYS)
            l_modliste = self.lua_val(self.PLUGIN_LISTS_KEYS)
            for idx, modname in l_modliste.items():
                modconf = l_conf[modname]
                self._p_confs[modname] = l_conf[modname]

        except Exception as err:
            print(err)
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print(traceback.print_tb(exc_traceback))
            Log().error("Init global-config raise error!Chk it !")
            sys.exit(1)

    def get(self, pluginname):
        return self._p_confs[pluginname]


@singleton
class PackConf(LuabaseTool):

    def __init__(self):
        super().__init__()

    def get_require_conf(self):
        require_conf = get_fileconf(Constant.REQUIRE_PACKINFO_FMT)
        return json.load(open(require_conf, "r"))

    def get_full_conf(self):
        full_conf = get_fileconf(Constant.REQUIRE_PACKINFO_FMT)
        return json.load(open(full_conf), "r")
